
// import * as d3 from "../lib/d3.js";
import * as d3 from "d3";
import {debounce, intersection} from "underscore";
import {$} from "../util/seq.js";

/**
 * Manages enabled/disabled state of z level buttons based on currently selected products.
 *
 * @param primaryLayerAgent
 * @param overlayLayerAgent
 */
export function defineZLevelManager(primaryLayerAgent, overlayLayerAgent) {
    const buttons = d3.select("[data-name=z_level]").selectAll("button");

    function updateDOM() {
        // Each layer describes the z levels it supports, which can be undefined if they aren't meaningful.
        // Because the same z level buttons control potentially both layers, the z levels to enable are the
        // intersection of the supported levels. If both layers don't use z levels, then disable all of them.

        const primary = primaryLayerAgent.value()?.supported_z_levels;
        const overlay = overlayLayerAgent.value()?.supported_z_levels;
        const enabled = new Set(primary && overlay ? intersection(primary, overlay) : (primary ?? overlay ?? []));
        buttons.attr("aria-disabled", function() {
            return !enabled.has(this.dataset.name);
        });
    }
    const updateDOM_debounced = debounce(updateDOM);

    primaryLayerAgent.on($`update`, updateDOM_debounced);
    overlayLayerAgent.on($`update`, updateDOM_debounced);
}
